package com.singerw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.singerw.annotations.OperLog;
import com.singerw.annotations.ResponseResult;
import com.singerw.annotations.UserId;
import com.singerw.annotations.UserName;
import com.singerw.service.ShareService;
import com.singerw.service.oss.OSSService;
import com.singerw.utils.JwtUtils;
import com.singerw.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

@RestController
@RequestMapping("/share")
public class ShareController {

    @Autowired
    private ShareService shareService;
    @Autowired
    private OSSService ossService;
 
    @PostMapping("/add")
    @OperLog(operModul = "分享模块",operType = "添加",operDesc = "增加一个分享")
    public String addShare(@RequestBody JSONObject jsonObject, @UserName String username, @UserId String userId) {
        String filePath = userId + jsonObject.get("path").toString();
        boolean isEncrypt = jsonObject.getBoolean("isEncrypt");
        return shareService.addShare(username, new Date(), filePath, isEncrypt);
    }

    /**
     * 获取分享信息
     * TODO 加入文件大小字段
     * @param jsonObject
     * @param res
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @PostMapping("/get")
    public String getShare(@RequestBody JSONObject jsonObject, HttpServletResponse res) throws IOException, ParseException {
        String key = jsonObject.get("key").toString();
        String pwd = jsonObject.get("pwd").toString();
        String shareData = shareService.getShare(key, pwd);
        if (shareData.equals("0")) {
            return ResultUtils.fail("秘钥错误");
        }
        JSONObject jsonObject1 = JSON.parseObject(shareData);
        long fileSize = ossService.getFileSize(jsonObject1.getString("filePath"));
        jsonObject1.put("fileSize",fileSize);
        //为了安全,此时不给用户具体的下载地址
        jsonObject1.remove("filePath");
        return ResultUtils.success(jsonObject1.toJSONString());
    }

    @GetMapping("/list")
    @OperLog(operModul = "分享模块",operType = "列表",operDesc = "后台获得分享列表")
    public String getShareList(){
       return shareService.getShareList();
    }

    @GetMapping("/list/me")
    @ResponseResult
    public String getShareMeList(@UserName String username){
        return shareService.getShareMeList(username);
    }

    @PostMapping("/remove")
    @ResponseResult
    @OperLog(operModul = "分享模块",operType = "删除分享",operDesc = "用户删除分享")
    public void removeShare(@RequestBody JSONObject jsonObject,@UserName String username){
        String key = jsonObject.getString("key");
        shareService.removeShare("Name:" + username + ":" +key);
        shareService.removeShare("Share:" + key);
    }







}
